<template>
  <div>
     <!-- 面包屑 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>
     <!-- 卡片视图 -->
     <el-card>
      <el-button type="primary" >添加角色</el-button>
      <el-table border stripe :data="roles">
      <el-table-column  type="expand">
        <template slot-scope="scope">
          <!-- 一级权限每一行 -->
          <el-row class="border_bottom" :class="index === 0 ? 'border_top' : ''" v-for="(item , index) in scope.row.children" :key="item.id">
            <!-- 一级权限  一级children是二级标题，二级children在三级标题里 -->
            <el-col :span="8">
              <el-tag>{{item.authName}}</el-tag>
              <i class="el-icon-caret-right"></i>
            </el-col>
            <!-- 生成二级权限 -->
             <el-col :span="16">
               <!-- 二级权限每一行 -->
               <el-row :class="index=== 0 ? '':'border-top'"  v-for="(item2,index) in item.children" :key="item2.id" >
                 <el-col  :span="5">
                     <el-tag type="success">{{item2.authName}}</el-tag>
                      <i class="el-icon-caret-right"></i>
                 </el-col>
                  <el-col  :span="19">
                    <!-- 生成三级权限 -->
                     <el-tag @close="removeTag(scope.row,item3.id)" closable v-for="item3 in item2.children" :key="item3.id" type="warning">{{item3.authName}}
                     </el-tag>
                 </el-col>
              </el-row>
             </el-col>
          </el-row>
        </template>
      </el-table-column>
      <!-- prop是后台规定的参数名字,也是接受后台数据渲染到页面上的， -->
      <el-table-column  label="#" type="index"></el-table-column>
      <el-table-column prop="roleName"  label="角色名称" ></el-table-column>
      <el-table-column prop="roleDesc" label="角色描述" ></el-table-column>
      <el-table-column label="操作" width="300px">
        <template slot-scope="scope">
        <el-button size="mini" type="primary" icon="el-i con-edit">编辑</el-button>
        <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button>
        <el-button @click="showSetRights(scope.row)" size="mini" type="warning" icon="el-icon-setting">分配权限</el-button>
        </template>
      </el-table-column>
    </el-table>
    </el-card>
   <!-- 分配权限对话框 -->
   <!-- data 传递整个属性数据 -->
   <!-- props: 配置树形控件的配置对象 -->
   <!--  -->
    <el-dialog
    @close="closeSetDialog"
    title="提示"
    :visible.sync="setRightsDialogVisible"
    width="30%">
    <el-tree ref = "tree"   node-key="id" default-expand-all show-checkbox :default-checked-keys="defkeys"  :data="rights" :props="treeDefaultProps"></el-tree>
    <span slot="footer" class="dialog-footer">
    <el-button @click="setRightsDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="submitSetRights = false">确 定</el-button>
    </span>
  </el-dialog>
  </div>
</template>

<script>
// 点击确定要做什么，要给谁添加什么名字，分配什么角色
export default {
  data () {
    return {
      // 来接收后台传过来的数据
      roles: [],
      setRightsDialogVisible: false,
      rights: [],
      // 配置树形控件的配置对象
      treeDefaultProps: {
        // label配置属性组件 显示文本的字段名
        label: 'authName',
        roleId: ''
      },
      defkeys: []
      // 获取默认选中的id
    }
  },

  created () {
    this.getRoles()
  },

  methods: {
    async getRoles () {
      const { data: res } = await this.$axios.get('roles')
      if (res.meta.status !== 200) return this.$message.error('获取数据失败')
      this.$message.success('更新数据成功')
      this.roles = res.data
    },
    removeTag (row, rightId) {
      this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        const { data: res } = await this.$axios.delete(`roles/${row.id}/rights/${rightId}`)
        if (res.meta.status !== 200) return this.$message.error('删除数据失败')
        // 这里的children是跟后台商量决定的
        row.children = res.data
        this.$message.success('删除成功')
      }).catch(() => {
        this.$message('已取消删除')
        // 简写的形式，因为文档内置简化好的
      })
    },
    // 点击显示对话框
    // 当我们点击分配权限，让它调用递归函数拿到角色分配整行的数据，吧上边数据参数传给row来接收，如果row等于false返回
    async showSetRights (row) {
      this.setRightsDialogVisible = true
      const { data: res } = await this.$axios.get('rights/tree')
      if (res.meta.status !== 200) return this.$message.error(('获取失败'))
      this.rights = res.data
      this.getAllkeys(row)
      // 拿到角色的id
      this.roleId = row.id
    },
    // 用递归的方式来进行遍历循环
    getAllkeys (row) {
      if (!row.children) return this.defkeys.push(row.id)
      row.children.forEach(item => {
        this.getAllkeys(item)
      })
    },
    closeSetDialog () {
      this.defkeys = []
    },
    async submitSetRights () {
      const checkedkeys = this.$refs.tree.getCheckdekeys()
      const halfCheckdkeys = this.$refs.tree.getHalfCheckdkeys()
      // 权限id
      const allCheckedkey = [...checkedkeys, ...halfCheckdkeys].join(',')
      console.log(allCheckedkey)
      // （key 和val一样就可以加简写）
      // this.roleId获得用户角色id
      const { data: res } = await this.$axios.put('roles/' + this.roleId + '/rights', { rids: allCheckedkey })
      if (res.meta.status !== 200) return this.$message.error('更新失败')
      this.setRightsDialogVisible = false
      this.getRoles()
      this.$message.success('更新数据成功')
    }

  }
}
</script>

<style scoped lang='less'>
.el-row{
  display: flex;
  align-items: center;
}
.border_top{
  border-top: 1px solid #eee;
}
.border_bottom{
  border-bottom: 1px solid #eee;
}
</style>
